package com.itboye.jinpuyiyuan.activity.me;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.UploadImageBean;
import com.itboye.jinpuyiyuan.bean.UserInfoBean;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.uploadmultipleimage.UploadImageUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.MultipartRequest;
import com.itboye.jinpuyiyuan.widget.camera.CameraActivity;
import com.itboye.jinpuyiyuan.widget.camera.PermissionTest;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 实名认证
 */
public class RealNameActivity extends BaseActivity implements Observer {
    //title
    private ImageView leftImg,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft,toobar;

    private EditText identifyEt,nameEt,birthdayEt,sexEt,phoneEt;
    private TextView real_ok,changeNumTv;
    //正 反
    private ImageView real_img01,real_img02;
    private BranchAddressPresenter presenter;
    private Intent intent;

    private String uid;
    private String type;
    private static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE=100;
    private static  final int CAMARE_IMAGE_ACTIVITY_REQUEST_CODE =112;
    private static final int WRITE_IMAGE_ACTIVITY_REQUEST_CODE =113;
    /**
     * 身份证正面的选择
     */
    private String localSelectPath01;
    /**
     * 身份证背面的选择
     */
    private String localSelectPath02;


    private int bit_width = 0;
    private int bit_height = 0;
    private ProgressDialog mProgressDialog;

    private String realName,idCard,sex,phone,birthday;
    private PopupWindow surePop,canclePop;
    private Timer timer;
    private int zId,fId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_real_name);
        leftTv.setVisibility(View.GONE);
        rightImg.setVisibility(View.GONE);
        tvTitle.setText("实名认证");

        intent=getIntent();


        presenter=new BranchAddressPresenter(this);
        uid= (String) SPUtils.get(getApplication(),null, Const.UID,"");




    }

    /**
     * 打开图库
     */
    private void pic() {
        if (!PermissionTest.isCameraPermission()){
            return;
        }
            Intent intent=new Intent(RealNameActivity.this,CameraActivity.class);
            startActivityForResult (intent,111);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }else {
                MAlert.alert("请手动添加读权限");
            }

        }
        if (requestCode == CAMARE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }else {
                MAlert.alert("请手动相机存储权限");
            }
        }
        if (requestCode == WRITE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }else {
                MAlert.alert("请手动相机写权限");
            }
        }
        if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)!=0){
            ActivityCompat.requestPermissions(RealNameActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }else if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                Manifest.permission.CAMERA)!=0){
            ActivityCompat.requestPermissions(RealNameActivity.this,
                    new String[]{Manifest.permission.CAMERA}, CAMARE_IMAGE_ACTIVITY_REQUEST_CODE);
        }else if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)!=0){
            ActivityCompat.requestPermissions(RealNameActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_IMAGE_ACTIVITY_REQUEST_CODE);
        }else {
           pic();
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //6.0添加拍照的权限
    private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    public static boolean isCameraPermission(Activity context, int requestCode) {
        if (Build.VERSION.SDK_INT >= 23) {
            int storagePermission = ActivityCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
            if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS_CAMERA_AND_STORAGE,
                        requestCode);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra("select_result");
            String paths = "";
            for (String path : pathList) {
                Log.i("ImagePathList", path);
                paths = pathList.get(0);
            }

            Bitmap bit = BitmapFactory.decodeFile(paths);
            bit_width = bit.getWidth();
            bit_height = bit.getHeight();
            if (type != null) {
                if (type.equals("zheng")) {
                    localSelectPath01 = paths;
                    real_img01.setImageBitmap(bit);
                } else {
                    localSelectPath02 = paths;
                    real_img02.setImageBitmap(bit);
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){

            case R.id.rlLeft:
            case R.id.leftImg:
                this.finish();
                break;
            case R.id.real_img01:// 添加身份证正面照片
                type = "zheng";

                if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)!=0){
                    ActivityCompat.requestPermissions(RealNameActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                }else if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                        Manifest.permission.CAMERA)!=0){
                    ActivityCompat.requestPermissions(RealNameActivity.this,
                            new String[]{Manifest.permission.CAMERA}, CAMARE_IMAGE_ACTIVITY_REQUEST_CODE);
                }else if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)!=0){
                    ActivityCompat.requestPermissions(RealNameActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_IMAGE_ACTIVITY_REQUEST_CODE);
                }else {
                    pic();
                }
                break;

            case R.id.real_img02:// 添加身份证背面照片
                type = "fan";
                if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)!=0){
                    ActivityCompat.requestPermissions(RealNameActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                }else if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                        Manifest.permission.CAMERA)!=0){
                    ActivityCompat.requestPermissions(RealNameActivity.this,
                            new String[]{Manifest.permission.CAMERA}, CAMARE_IMAGE_ACTIVITY_REQUEST_CODE);
                }else if (  ActivityCompat.checkSelfPermission(RealNameActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)!=0){
                    ActivityCompat.requestPermissions(RealNameActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_IMAGE_ACTIVITY_REQUEST_CODE);
                }else {
                    pic();
                }
                break;
            case R.id.real_ok:
                realName=nameEt.getText().toString().trim();
                idCard=identifyEt.getText().toString().trim();
                sex=getSexInt(sexEt.getText().toString().trim())+"";
                phone=phoneEt.getText().toString().trim();
                birthday=birthdayEt.getText().toString().trim();

                real_ok.setEnabled(true);
                if (realName.equals("")){
                    MAlert.alert("姓名不能为空");
                }else if (idCard.equals("")){
                    MAlert.alert("身份证号不能为空");
                }else if (birthday.equals("")){
                    MAlert.alert("生日不能为空");
                } else if (!birthday.contains("-")){
                    MAlert.alert("生日格式不对,请重新填写,格式例如 1990-11-10");
                }  else if (sex.equals("0")||sexEt.getText().toString().equals("")){
                    MAlert.alert("性别不能为空");
                }else if (phone.equals("")){

                    MAlert.alert("电话号码不能为空");
                }else {
                    showProgress();
//                    showProgressDialog("请求提交中,请稍后", false);
                    String[] img = {localSelectPath01, localSelectPath02};
                    String url = Const.updaloadURL;
                    Map<String, String> params = new HashMap<String, String>();
                   // ['avatar', 'other', 'sys_avatar', 'identity'];
                    params.put("uid", uid);
                    params.put("type", "identity");
                    params.put("md5","" );
                    params.put("sha1", "");

//                    params.put("uid", uid);
//                    params.put("type", "ID");
                    File f1 = null;
                    File f2 = null;
                    if (localSelectPath01 == null || localSelectPath02 == null) {
                        MAlert.alert("请先选择有效图片");
                        mProgressDialog.dismiss();
                        return;
                    }
                    f1 = new File(localSelectPath01);
                    f2 = new File(localSelectPath02);

                    params.put("ori_name",f1.getName());

                   MultipartRequest multipartRequest = new MultipartRequest(Const.updaloadURL, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            System.out.println(" onResponse    ------>>>>" + response);
//                            Gson gson = new Gson();
//                            UploadImageBean uploadImageBean=null;
//                            try {
//                                uploadImageBean = gson.fromJson(response, UploadImageBean.class);
//                                if (uploadImageBean != null) {
//                                    if (uploadImageBean.getCode() != 0) {
//                                        uploadResult.uploadFail(new VolleyError(uploadImageBean.getData().toString()));
//                                    } else {
//                                        uploadResult.uploadSuccess(uploadImageBean);
//                                    }
//                                } else {
//                                    uploadResult.uploadFail(new VolleyError());
//                                }
//                            }catch (Exception e){
//                                uploadResult.uploadFail(new VolleyError(response));
//                            }

                            try {
                                JSONObject object = new JSONObject(response);
                                JSONObject data = object.getJSONObject("data");
                                if (object.getInt("code")==0){
                                    MAlert.alert("正面图片上传成功");
                                }
                                zId= Integer.parseInt(data.getString("id"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(final VolleyError error) {
                           MAlert.alert("正面图片上传失败");
                        }
                    }, "by_image", f1, params);
                    multipartRequest.setRetryPolicy(new DefaultRetryPolicy(100000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                 MyApplication.addRequest(multipartRequest);

                    params.put("ori_name",f2.getName());
                MultipartRequest multipartRequest1 = new MultipartRequest(Const.updaloadURL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            JSONObject data = object.getJSONObject("data");
                            if (object.getInt("code")==0) {
                                MAlert.alert("反面图片上传成功");
                            }
                            fId = Integer.parseInt(data.getString("id"));
                            presenter.verifyUserIdCard(uid,idCard,birthday,realName,sex,phone,"itboye",zId,fId);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(final VolleyError error) {
                       MAlert.alert("反面身份证照上传失败");
                        MAlert.alert("认证失败");
                        mProgressDialog.dismiss();
                    }
                },"by_image", f2, params);
                    multipartRequest1.setRetryPolicy(new DefaultRetryPolicy(100000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                MyApplication.addRequest(multipartRequest1);

//
//                    new UploadImageUtils().beginUpload(params,"by_image",f1,new UploadImageUtils.UploadResult(){
//
//                        @Override
//                        public void uploadSuccess(UploadImageBean response) {
//                            zId=response.getData().get(0).getId();
//                        }
//
//                        @Override
//                        public void uploadFail(VolleyError error) {
//                            MAlert.alert("上传失败"+error.getMessage());
//                        }
//                    } );
//                    params.put("ori_name",f2.getName());
//                    new UploadImageUtils().beginUpload(params,"by_image",f2,new UploadImageUtils.UploadResult(){
//
//                        @Override
//                        public void uploadSuccess(UploadImageBean response) {
//
//                            fId=response.getData().get(0).getId();
//                        }
//
//                        @Override
//                        public void uploadFail(VolleyError error) {
//                            MAlert.alert("上传失败"+error.getMessage());
//                        }
//                    });


//                    new UploadImageUtils().beginUpload(params,"image[]",f,this);
//                    MultipartRequest request = new MultipartRequest(url,
//                            new Response.Listener<String>() {
//                                @Override
//                                public void onResponse(String response) {
//                                    //  ByAlert.alert("上传成功");
//                                    try {
//                                        closeProgressDialog();
//                                    } catch (Exception e) {
//                                    }
//                                    presenter.verifyUserIdCard(uid,idCard,"",realName,sex,phone,"itboye",);
////                                    userPresenter.getRealName(uid, realname, ibnumber, yinhangka, phone, code);
//                                }
//                            }, new Response.ErrorListener() {
//
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
//                            try {
//                                closeProgressDialog();
//                            } catch (Exception e) {
//                            }
//                            MAlert.alert("上传错误" + error.getMessage());
//                        }
//                    }, "image[]", f, params, 500, bit_width, bit_height); // 注意这个key必须是f_file[],后面的[]不能少
//                    MyApplication.addRequest(request);
//                    showDialog1();
                }

                break;
        }
    }


//    public void toUpImg(File file){
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("uid", uid);
//        params.put("type", "avatar");
//        params.put("md5","" );
//        params.put("sha1", "");
//        params.put("ori_name",file.getName());
//        new UploadImageUtils().beginUpload(params, "by_image",file ,this);
//        showProgress();
//    }



    public void showProgress(){
        mProgressDialog=new ProgressDialog(this);
        mProgressDialog.setMessage("正在上传中，请稍后...");
        mProgressDialog.show();
    }

    private Integer getFileInt(File file){

        return 0;
    }
    @Override
    public void update(Observable o, Object arg) {

        ResultEntity resultEntity = handlerError(arg);

        if (resultEntity!=null){

            if (resultEntity.getEventType()== BranchAddressPresenter.By_UserIdCard_info_success){//获取用户身份信息
              UserInfoBean user= (UserInfoBean) resultEntity.getData();
              realName=user.getId_info().getReal_name();
              idCard=user.getId_info().getCard_no();
//              MAlert.alert("获取用户信息成功");
            }else if (resultEntity.getEventType()== BranchAddressPresenter.By_UserIdCard_info_fail){

//                MAlert.alert("获取用户信息失败");
            }else if (resultEntity.getEventType()== BranchAddressPresenter.By_UserIdCard_update_success){//更改用户身份信息
                MAlert.alert("数据保存成功");
                real_ok.setEnabled(true);
                mProgressDialog.dismiss();
                SPUtils.put(RealNameActivity.this,uid,"isVerify",true);

                setResult(200,intent.putExtra("isSuccess",true));
                RealNameActivity.this.finish();
            }else if (resultEntity.getEventType()== BranchAddressPresenter.By_UserIdCard_update_fail){
//                MAlert.alert("数据保存失败");
                mProgressDialog.dismiss();
                setResult(200,intent.putExtra("isSuccess",false));
            }else if (resultEntity.getEventType()== BranchAddressPresenter.By_UserIdCard_verify_success){
                 MAlert.alert("认证成功");
                mProgressDialog.dismiss();
                SPUtils.put(RealNameActivity.this,uid,"isVerify",true);

                setResult(200,intent.putExtra("isSuccess",true));
                RealNameActivity.this.finish();
            }else if (resultEntity.getEventType()== BranchAddressPresenter.By_UserIdCard_verify_fail){
                MAlert.alert(resultEntity.getMsg()+"失败");
                mProgressDialog.dismiss();
            }


        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public void showDialog1(){

        View convertView = LayoutInflater.from(this).inflate(R.layout.dialog_realname, null);
        surePop=new PopupWindow(convertView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        surePop.setAnimationStyle(R.style.popupwindow_anim_style);
        surePop.setFocusable(true);
        TextView idCardTv=convertView.findViewById(R.id.idCardTv);
        TextView nameTv= convertView.findViewById(R.id.nameTv);
        idCardTv.setText(identifyEt.getText().toString());
        nameTv.setText(nameEt.getText().toString());
        final TextView sureTv=convertView.findViewById(R.id.sureTv);
        TextView cancelTv=convertView.findViewById(R.id.cancelTv);
        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                surePop.dismiss();
                presenter.updatePersonInfo(uid,identifyEt.getText().toString(),nameEt.getText().toString());
            }
        });
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                surePop.dismiss();
                real_ok.setEnabled(true);
            }
        });
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                surePop.dismiss();
                real_ok.setEnabled(true);
            }
        });
        convertView.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        convertView.setFocusableInTouchMode(true); //comment by
        surePop.showAtLocation(convertView, Gravity.TOP,0,0);



    }

    //显示限制次数的pop
    public void showDialog2(){
        View convertView = LayoutInflater.from(this).inflate(R.layout.popwind_realname_limit, null);
        canclePop=new PopupWindow(convertView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        canclePop.setAnimationStyle(R.style.popupwindow_anim_style);
        canclePop.setFocusable(true);

        TextView limitTv= convertView.findViewById(R.id.limitTv);
//        limitTv.setText("一天只能修改"+limit+"次");

        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canclePop.dismiss();
            }
        });

        convertView.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        convertView.setFocusableInTouchMode(true); //comment by
        canclePop.showAtLocation(convertView, Gravity.TOP,0,0);

    }
    public int getSexInt(String s){
        //0未知/1男/2女
        if (s.contains("男")){
            return 1;
        }else if (s.contains("女")){
            return 2;
        }
        return 0;
    }

    @Override
    public void finish() {
        super.finish();
    }

}
